package com.hu.bgp.server;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Intercept hiermee calls naar de .html files om een 'permanent' (aka
 * persistent) cookie te zetten.
 * 
 * @author ejvos
 */
public class BgpCookieFilterImpl implements Filter
{
	public static final String COOKIE_NAME = "BgpPermaCookie";

	public void init(FilterConfig filterConfig) throws ServletException
	{
	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
	{
		System.out.println("BgpCookieFilterImpl.doFilter");
		if (request instanceof HttpServletRequest && response instanceof HttpServletResponse)
		{
			HttpServletRequest hrequest = (HttpServletRequest) request;
			HttpServletResponse hresponse = (HttpServletResponse) response;
			String guid = findUserUuidFromCookie(hrequest);
			if (guid == null)
			{
				Cookie newCookie = new Cookie(COOKIE_NAME, UUID.randomUUID().toString());
				newCookie.setMaxAge(60 * 60 * 24 * 365);
				hresponse.addCookie(newCookie);
			}
		}
		filterChain.doFilter(request, response);
	}

	public void destroy()
	{
	}

	public static String findUserUuidFromCookie(HttpServletRequest request)
	{
		String result = null;
		if (request.getCookies() != null)
		{
			for (Cookie cookie : request.getCookies())
			{
				if (cookie.getName().equals(COOKIE_NAME))
				{
					result = cookie.getValue();
					break;
				}
			}
		}
		return result;
	}
}
